package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

public class TcpEchoServer1 {
    ServerSocket serverSocket = null;

    TcpEchoServer1(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动");
        ExecutorService service = Executors.newCachedThreadPool();
        while (true) {
            Socket socket = serverSocket.accept();
            service.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        solve(socket);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    private void solve(Socket socket) throws IOException {
        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream()) {
            System.out.printf("[%s:%d] 客户端上线\n", socket.getInetAddress(), socket.getPort());
            Scanner scanner = new Scanner(inputStream);
            while(true) {
                //等待响应
                if(!scanner.hasNext()) {
                    break;
                }
                String request = scanner.next();
                String respond = process(request);
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(respond);
                printWriter.flush();
                System.out.printf("[%s:%d] req=%s, resp=%s\n", socket.getInetAddress(), socket.getPort(),
                        request, respond);
            }
        } finally {
            System.out.printf("[%s:%d] 客户端下线\n", socket.getInetAddress(), socket.getPort());
            socket.close();
        }
    }
    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer1 server1 = new TcpEchoServer1(1314);
        server1.start();
    }
}
